/*
 * @Description: 动态组件工具类
 * @Author: DHL
 * @Date: 2022-01-01 15:18:18
 * @LastEditors: DHL
 * @LastEditTime: 2023-07-13 14:51:56
 */

const dynamicComponentViewsModules = import.meta.glob('../views/**/*.{vue,tsx}')

const dynamicComponentViewsKeys = Object.keys(dynamicComponentViewsModules)

/**
 * 动态导入组件
 * @param component
 * @returns
 */
export function dynamicComponentImport(component: string) {
  if (!component) {
    console.warn('请正确配置组件')
    return Promise.reject()
  }

  const viewsMatchKeys = dynamicComponentViewsKeys.filter((key) => {
    const k = key.replace('../views', '')
    const startFlag = component.startsWith('/')
    const endFlag = component.endsWith('.vue') || component.endsWith('.tsx')
    const startIndex = startFlag ? 0 : 1
    const lastIndex = endFlag ? k.length : k.lastIndexOf('.')
    return k.substring(startIndex, lastIndex) === component
  })

  if (viewsMatchKeys?.length > 0) {
    const matchKey = viewsMatchKeys[0]
    return dynamicComponentViewsModules[matchKey]()
  }

  console.warn(
    'Please do not create `.vue` and `.TSX` files with the same file name in the same hierarchical directory under the views folder. This will cause dynamic introduction failure'
  )

  return Promise.reject()
}
